<template>
  <div class="dashboard-container">
    <!-- 欢迎信息 -->
    <div class="welcome-section">
      <div class="welcome-info">
        <h2>欢迎回来，{{ userName }}</h2>
        <p class="time-info">{{ currentTime }}</p>
      </div>
    </div>

    <!-- 管理员统计卡片 -->
    <div v-if="userRole === 'ROLE_ADMIN'" class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card card-blue">
            <div class="card-icon">
              <el-icon><VideoPlay /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">总视频数</div>
              <div class="card-value">{{ stats.videoCount }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+10%</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card card-green">
            <div class="card-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">总播放量</div>
              <div class="card-value">{{ stats.viewCount }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+15%</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card card-orange">
            <div class="card-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">用户数量</div>
              <div class="card-value">{{ stats.userCount }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+5%</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card card-purple">
            <div class="card-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">收藏数量</div>
              <div class="card-value">{{ stats.favoriteCount }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+8%</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 作者统计卡片 -->
    <div v-if="userRole === 'ROLE_AUTHER'" class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card card-blue">
            <div class="card-icon">
              <el-icon><VideoPlay /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">我的视频</div>
              <div class="card-value">{{ authorStats.myVideoCount }}</div>
              <div class="card-trend">
                本周上传 <span class="up">+{{ authorStats.weeklyUploads }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card card-green">
            <div class="card-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">总播放量</div>
              <div class="card-value">{{ authorStats.totalViews }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+{{ authorStats.viewIncrease }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card card-orange">
            <div class="card-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">获得收藏</div>
              <div class="card-value">{{ authorStats.totalFavorites }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+{{ authorStats.favoriteIncrease }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card card-purple">
            <div class="card-icon">
              <el-icon><DataLine /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">互动数</div>
              <div class="card-value">{{ authorStats.interactions }}</div>
              <div class="card-trend">
                较昨日 <span class="up">+{{ authorStats.interactionIncrease }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 管理员快捷操作 -->
    <div v-if="userRole === 'ROLE_ADMIN'" class="quick-actions">
      <h3 class="section-title">快捷操作</h3>
      <el-row :gutter="20">
        <el-col :span="6" v-for="action in adminActions" :key="action.name">
          <div class="action-card" @click="action.handler">
            <el-icon class="action-icon"><component :is="action.icon" /></el-icon>
            <span class="action-name">{{ action.name }}</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 作者快捷操作 -->
    <div v-if="userRole === 'ROLE_AUTHER'" class="quick-actions">
      <h3 class="section-title">快捷操作</h3>
      <el-row :gutter="20">
        <el-col :span="6" v-for="action in authorActions" :key="action.name">
          <div class="action-card" @click="action.handler">
            <el-icon class="action-icon"><component :is="action.icon" /></el-icon>
            <span class="action-name">{{ action.name }}</span>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 系统公告 -->
    <div class="announcement-section">
      <h3 class="section-title">系统公告</h3>
      <el-card class="announcement-card">
        <el-timeline>
          <el-timeline-item
            v-for="notice in announcements"
            :key="notice.id"
            :timestamp="notice.time"
            :type="notice.type">
            <h4>{{ notice.title }}</h4>
            <p>{{ notice.content }}</p>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>


    <!-- 待办事项 -->
    <div class="todo-section">
      <el-row :gutter="20">
        <!-- 待审核视频 -->
        <el-col :span="12" v-if="userRole === 'ROLE_ADMIN'">
          <el-card class="todo-card">
            <template #header>
              <div class="todo-header">
                <h4>待审核视频</h4>
                <el-button type="primary" link @click="router.push('/examine')">查看全部</el-button>
              </div>
            </template>
            <el-table :data="pendingVideos" style="width: 100%" size="small">
              <el-table-column prop="title" label="视频标题" />
              <el-table-column prop="author" label="作者" width="100" />
              <el-table-column prop="submitTime" label="提交时间" width="150" />
            </el-table>
          </el-card>
        </el-col>

        <!-- 最新评论 -->
        <el-col :span="12">
          <el-card class="todo-card">
            <template #header>
              <div class="todo-header">
                <h4>最新评论</h4>
                <el-button type="primary" link @click="router.push('/commentList')">查看全部</el-button>
              </div>
            </template>
            <el-table :data="recentComments" style="width: 100%" size="small">
              <el-table-column prop="content" label="评论内容" show-overflow-tooltip />
              <el-table-column prop="user" label="用户" width="100" />
              <el-table-column prop="time" label="时间" width="150" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { VideoPlay, View, User, Star, Upload, Setting, Edit, DataLine, Message, PieChart } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()
const userName = localStorage.getItem('userName')
const userRole = localStorage.getItem('userType')
const currentTime = ref('')
const videoCount = ref('')
const viewCount = ref('')
const userCount = ref('')
const favoriteCount = ref('')
const autherVideoCount = ref('')
const autherviewCount = ref('')
// const autherUserCount = ref('')
const autherFavoriteCount = ref('')
// 管理员统计数据
const stats = ref({
  videoCount: videoCount,
  viewCount: viewCount,
  userCount: userCount,
  favoriteCount: favoriteCount
})

const statsvideoCount = async () =>{
  try{
    const res = await request.get("/details/VideoListCount");
    videoCount.value = res.data.data;
  }catch (error) {
    if (error.response) {
    // 请求已发出，但服务器响应了状态码不在2xx范围内的内容
    console.error('服务器响应错误:', error.response.status, error.response.data);
    // 你可以根据状态码做不同的处理
    if (error.response.status === 402 || error.response.status === 405) {
      // 处理405错误
    localStorage.removeItem('token')
    localStorage.removeItem('userName')
    localStorage.removeItem('menus')
    localStorage.removeItem('userType')
    // 重定向到登录页面
    router.push('/login')
    }
  } else if (error.request) {
    // 请求已发出，但没有收到响应
    console.error('请求已发送，但未收到响应:', error.request);
  } else {
    // 其他错误（如配置错误导致请求未发送）
    console.error('错误:', error.message);
  }
  }
}
//总浏览量
const statsviewCount = async () =>{
  const res = await request.get("/details/viewCountListCount");
  viewCount.value = res.data.data;
}
//用户量
const statsuserCount = async () =>{
  const res = await request.get("/user/UserListCount");
  userCount.value = res.data.data;
}
//总收藏量
const statsfavoriteCount = async () =>{
  const res = await request.get("/details/favoriteCountListCount");
  favoriteCount.value = res.data.data;
} 
// 作者统计数据
const authorStats = ref({
  myVideoCount: autherVideoCount,
  weeklyUploads: '3',
  totalViews: autherviewCount,
  viewIncrease: '156',
  totalFavorites: autherFavoriteCount,
  favoriteIncrease: '12',
  interactions: '456',
  interactionIncrease: '8'
})

//作者视频总数量
const  autherVideoCountList= async () =>{
  const res = await request.post(`/details/autherVideoCount/${userName}`);
  autherVideoCount.value = res.data.data;
}

//总浏览量
const autherViewCountList = async () =>{
  const res = await request.post(`/details/autherViewCountList/${userName}`);
  autherviewCount.value = res.data.data;
}
//用户量
// const autherUserCountList = async () =>{
//   const res = await request.post(`/user/autherUserListCount/${userName}`);
//   autherUserCount.value = res.data.data;
// }
//总收藏量
const autherFavoriteCountList = async () =>{
  const res = await request.post(`/details/autherFavoriteCountList/${userName}`);
  autherFavoriteCount.value = res.data.data;
} 

// const statsuserCount = async () =>{
//   const res = await request.get("/user/UserListCount");
//   userCount.value = res.data.data;
// }
// const statsfavoriteCount = async () =>{
//   const res = await request.get("/details/favoriteCountListCount");
//   favoriteCount.value = res.data.data;
// } 
// 系统公告
const announcements = ref([
  {
    id: 1,
    title: '系统升级通知',
    content: '系统将于本周六凌晨2点进行升级维护，预计持续2小时',
    time: '2024-01-20',
    type: 'warning'
  },

  {
    id: 2,
    title: '春节放假通知',
    content: '春节期间（2月10日-2月17日）客服服务时间调整为9:00-18:00',
    time: '2024-01-15',
    type: 'info'
  }
])

// 待审核视频
const pendingVideos = ref([
  { title: '2024春节晚会花絮', author: '张三', submitTime: '2024-01-20 10:30' },
  { title: '年夜饭美食vlog', author: '李四', submitTime: '2024-01-20 09:15' },
  { title: '新年祝福视频', author: '王五', submitTime: '2024-01-19 18:20' }
])

// 最新评论
const recentComments = ref([
  { content: '视频很精彩，期待更新', user: '用户A', time: '2024-01-20 11:30' },
  { content: '画面太美了，收藏了', user: '用户B', time: '2024-01-20 10:45' },
  { content: '讲解很详细，学到了很多', user: '用户C', time: '2024-01-20 09:20' }
])

// 管理员快捷操作
const adminActions = [
  { name: '用户管理', icon: User, handler: () => router.push('/user') },
  { name: '数据统计', icon: DataLine, handler: () => router.push('/') },
  { name: '内容审核', icon: Edit, handler: () => router.push('/examine') },
  { name: '系统设置', icon: Setting, handler: () => router.push('/settings') }
]

// 作者快捷操作
const authorActions = [
  { name: '上传视频', icon: Upload, handler: () => router.push('/uploadVideo') },
  { name: '我的作品', icon: VideoPlay, handler: () => router.push('/myVideos') },
  { name: '数据分析', icon: PieChart, handler: () => router.push('/analysis') },
  { name: '消息中心', icon: Message, handler: () => router.push('/messages') }
]

// 更新时间
const updateTime = () => {
  const now = new Date()
  const hours = now.getHours()
  let greeting = '早上好'
  if (hours >= 12 && hours < 18) {
    greeting = '下午好'
  } else if (hours >= 18) {
    greeting = '晚上好'
  }
  currentTime.value = `${greeting}，今天是 ${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`
}

// 获取统计数据
// const getStats = async () => {
//   try {
//     const res = await request.get('/api/dashboard/stats')
//     if (userRole === 'ROLE_ADMIN') {
//       stats.value = res.data.admin
//     } else {
//       authorStats.value = res.data.author
//     }
//   } catch (error) {
//     console.error('获取统计数据失败:', error)
//   }
// }

// // 获取系统公告
// const getAnnouncements = async () => {
//   try {
//     const res = await request.get('/api/announcements')
//     announcements.value = res.data
//   } catch (error) {
//     console.error('获取公告失败:', error)
//   }
// }

// // 获取待办事项
// const getTodoList = async () => {
//   try {
//     if (userRole === 'ROLE_ADMIN') {
//       const res = await request.get('/api/videos/pending')
//       pendingVideos.value = res.data
//     }
//     const commentsRes = await request.get('/api/comments/recent')
//     recentComments.value = commentsRes.data
//   } catch (error) {
//     console.error('获取待办事项失败:', error)
//   }
// }

onMounted(() => {
  statsvideoCount()
  statsviewCount()
  statsuserCount()
  statsfavoriteCount()
  autherVideoCountList()
  autherViewCountList()
  // autherUserCountList()
  autherFavoriteCountList()
  updateTime()
  // getStats()
  // getAnnouncements()
  // getTodoList()
  setInterval(updateTime, 60000) // 每分钟更新一次时间
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-section {
  margin-bottom: 30px;
  background: linear-gradient(135deg, #6b73ff 0%, #000dff 100%);
  padding: 30px;
  border-radius: 12px;
  color: white;
}

.welcome-info h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.time-info {
  margin-top: 10px;
  opacity: 0.9;
}

.stat-cards {
  margin-bottom: 30px;
}

.stat-card {
  padding: 20px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  transition: transform 0.3s;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.card-blue {
  background: linear-gradient(135deg, #42b0ff 0%, #0085ff 100%);
  color: white;
}

.card-green {
  background: linear-gradient(135deg, #69f0ae 0%, #00e676 100%);
  color: white;
}

.card-orange {
  background: linear-gradient(135deg, #ffa726 0%, #ff9100 100%);
  color: white;
}

.card-purple {
  background: linear-gradient(135deg, #ba68c8 0%, #9c27b0 100%);
  color: white;
}

.card-icon {
  font-size: 40px;
  margin-right: 20px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  opacity: 0.9;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 5px 0;
}

.card-trend {
  font-size: 12px;
  opacity: 0.9;
}

.up {
  color: #fff;
  font-weight: bold;
}

.section-title {
  margin: 20px 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.announcement-section {
  margin-bottom: 30px;
}

.announcement-card {
  background: #fff;
  border-radius: 12px;
}

.todo-section {
  margin-top: 30px;
}

.todo-card {
  margin-bottom: 20px;
}

.todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.action-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #eee;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.action-icon {
  font-size: 30px;
  margin-bottom: 10px;
  color: #409EFF;
}

.action-name {
  font-size: 14px;
  color: #606266;
}

@media screen and (max-width: 768px) {
  .el-col {
    margin-bottom: 20px;
  }
  
  .stat-card {
    margin-bottom: 15px;
  }

  .todo-section .el-col {
    width: 100%;
  }
}
</style>
